<?php
/*
Copyright (c) 2010 Samuel Stevens

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
if (!defined('INDEX')) {exit("This script cannot be called directly");}

class AutoDBRecord implements ArrayAccess
{
	var $db;
	var $pk;
	var $table;
	var $fields = array();
	var $lastSaveFields = array();
	var $noQuoteFields = array();
	var $reloadOnSave = False;
	var $newRecord = False;
	function AutoDBRecord(array $fields,AutoDB $autodb)
	{
		$this->db = AutoDB::GetDB();
		if (count($fields) == 0)
			$this->newRecord = True;
		else
		{
			$this->fields = $fields;
			$this->lastSaveFields = $fields;
		}
			
		$this->pk = $autodb->PrimaryKey();
		$this->table = $autodb->TableName();
	}
	function __get($field)
	{
		if (isset($this->fields[$field]))
			return $this->fields[$field];
		throw new DatabaseException("Unknown field $field");
	}
	function __set($field, $value)
	{
		$this->fields[$field] = db_escape($value);
		$this->noQuoteFields[$field] = False;
	}
	function Set($field,$value,$dbescape=True)
	{
		$this->fields[$field] = ($dbescape) ? db_escape($value) : $value;
		$this->noQuoteFields[$field] = False;
		return $this;
	}
	function SetNoQuote($field,$value=Null, $reloadOnSave=True)
	{
		if ($value !== Null)
			$this->Set($field,$value, False);
		$this->noQuoteFields[$field] = True;
		$this->ReloadOnSave($reloadOnSave);
		return $this;
	}
	function ReloadOnSave($value=True)
	{
		if ($value == True)
			$this->reloadOnSave = True;
		else
			$this->reloadOnSave = False;
		
		return $this;
	}
	function Get($field, $default=Null)
	{
		if (isset($this->fields[$field]))
			return $this->fields[$field];
		else 
			return $default;
	}
	function AsArray()
	{
		return $this->fields;
	}
	function Save()
	{
		$result = False;
		if ($this->newRecord)
			$result = $this->_New();
		else
			$result = $this->_Update();
		$this->lastSaveFields = $this->fields;
		if ($this->reloadOnSave == True)
		{
			$newFields = $this->db->query("Select * From `$this->table` Where `$this->pk` = $this->fields[$this->pk] Limit 1");
			if ($newFields == False)
				throw new DatabaseException("Could not reload record #$this->fields[$this->pk] from database after save");
			$this->fields = $newFields;
		}
		return $result;
	}
	function Delete()
	{
		if ($this->newRecord)
			throw new DatabaseException("Cannot delete, no record selected");
		$id = $this->fields[$this->pk];
		$query = "Delete From `$this->table` Where `$this->pk` = $id Limit 1";
		$result = $this->db->query($query,False);
		if ($result == True)
		{
			$this->lastSaveFields = array();
			unset($this->fields[$this->pk]);
			$this->newRecord = True;
		}
		return $result;
	}
	private function _New()
	{
		if (count($this->fields) == 0)
		{
			trigger_error("Cannot save record, no fields set",E_USER_ERROR);
			return False;
		}
		$query = "Insert Into `$this->table` Set ";
		$query .= $this->_Fields();
		$result = $this->db->query($query,False);
		if ($result == False)
			return False;
		$id = $this->db->last_insert_id();
		$this->fields[$this->pk] = $id;
		$this->newRecord = False;
		return $id;
	}
	private function _Update()
	{
		$id = $this->fields[$this->pk];
		$fields = $this->_Fields();
		if (empty($fields))
			return True;
		$query = "Update `$this->table` Set ";
		$query .= $fields;
		$query .= " Where `$this->pk` = $id Limit 1";
		return $this->db->query($query,False);
	}
	private function _Fields()
	{
		$lastSave = $this->lastSaveFields;
		$query = "";
		foreach ($this->fields as $name=>$value)
		{
			if ($name == $this->pk)
				continue;
			if (isset($lastSave[$name]) && $lastSave[$name] === $value)
				continue;
				
			$noQuote = (isset($this->noQuoteFields[$name]) && $this->noQuoteFields[$name] == True);
			
			if (is_string($value) && !$noQuote)
				$query .= "`$name` = '$value', ";
			else
				$query .= "`$name` = $value, ";
		}
		$query = substr($query, 0, strlen($query)-2); //trim last Comma-Space
		return $query;
	}
	
	
	//ArrayAccess Functions
	function offsetSet($offset, $value) 
	{
		if (is_null($offset)) {
			$this->fields[] = $value;
		} else {
			$this->fields[$offset] = $value;
		}
	}
	function offsetExists($offset) 
	{
		return isset($this->fields[$offset]);
	}

	function offsetUnset($offset) 
	{
		unset($this->fields[$offset]);
	}

	function offsetGet($offset) 
	{
		return isset($this->fields[$offset]) ? $this->fields[$offset] : null;
	}
}
?>